package com.springboot.example.mybatis.servlet;

import org.apache.log4j.Logger;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;

/**
 * 消息处理
 * Created by WangYang on 14-1-8.
 */
@WebServlet(urlPatterns="/servlet/message", description="微信认证servlet")
public class MessageServlet extends HttpServlet {

    private static Logger logger = Logger.getLogger(MessageServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            // 响应消息
            PrintWriter out = response.getWriter();
            out.print("111");
            out.close();
        } catch (Throwable t) {
            logger.error(t);
        }
    }

    public String inputStreamToString(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }


    /**
     * 获取toUserName
     *
     * @param xmltext
     * @return
     */
    public static String getUserName(String xmltext) throws Exception {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xmltext);
            InputSource is = new InputSource(sr);
            org.w3c.dom.Document document = db.parse(is);
            org.w3c.dom.Element root = document.getDocumentElement();
            NodeList nodelist = root.getElementsByTagName("ToUserName");
            return nodelist.item(0).getTextContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
